package cn.jee.controller;

import cn.jee.entity.Product;
import cn.jee.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class UploadController {

  @Autowired
  private ProductRepository productRepository;

  @PostMapping("/upload")
  @ResponseBody
  public String upload(@RequestParam("file") MultipartFile file,
                       @RequestParam("productId") Long productId) throws IOException {
    if (file.isEmpty()) {
      return "{\"error\": \"文件为空\"}";
    }

    String fileName = file.getOriginalFilename();
    String savePath = "D:\\" + fileName;
    File dest = new File(savePath);
    file.transferTo(dest);

    Product product = productRepository.findById(productId).orElseThrow();
    product.setImagePath("/images/" + fileName);
    productRepository.save(product);

    return "{\"success\": true}";
  }

  //局部异常处理
  @ExceptionHandler(IOException.class)
  @ResponseBody
  public String handleIOException(IOException e) {
    return "{\"error\": \"上传失败: " + e.getMessage() + "\"}";
  }

}